package cn.woochen.mvvmframe.activity

import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import cn.woochen.comlib.adapter.RecycleViewDivider
import cn.woochen.comlib.util.ResourceUtil
import cn.woochen.comlib.util.ext.dp
import cn.woochen.mvvmframe.R
import cn.woochen.mvvmframe.adapter.ArticleAdapter
import cn.woochen.mvvmframe.bean.HomeBannerBean
import cn.woochen.mvvmframe.config.BaseActivity
import cn.woochen.mvvmframe.config.ext.parseState
import cn.woochen.mvvmframe.databinding.ActivityNetBinding
import cn.woochen.mvvmframe.databinding.ViewNetHeaderBinding
import cn.woochen.mvvmframe.viewmodels.NetViewModel
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.CircleIndicator
import kotlinx.coroutines.launch


/**
 *类描述：网络请求示例类
 *@author woochen
 *@time 2021/7/28 18:00
 */
class NetActivity : BaseActivity<ActivityNetBinding, NetViewModel>() {

    private val mArticleAdapter by lazy {
        ArticleAdapter()
    }

    private lateinit var mHeadViewBinding: ViewNetHeaderBinding

    override fun setContentView(): Int = R.layout.activity_net

    override fun initData() {
        setStatusBarStyle(false)
        initWidgets()
        requestData()
        getBannerData()
    }

    override fun initListener() {
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                mPage = 0
                getBannerData()
                requestData()
                refreshLayout.finishRefresh()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                mPage++
                requestData()
            }
        })
    }

    override fun registerNecessaryObserver() {
        super.registerNecessaryObserver()
        lifecycleScope.launch {
            mViewModel.homeBannerInfo.collect {
                parseState(it, { list: List<HomeBannerBean>?, _, _, _ ->
                    list?.let {
                        initBanner(list)
                    }
                })
            }
        }

        lifecycleScope.launch {
            mViewModel.articleListInfo.collect { it ->
                parseState(it, { articleBean, _, _, _ ->
                    articleBean?.let {
                        val datas = articleBean.datas
                        if (mPage == 0) {
                            mArticleAdapter.setList(datas)
                        } else {
                            if (!datas.isNullOrEmpty()) mArticleAdapter.addData(datas)
                        }
                        if (it.over) mBinding.refreshLayout.finishLoadMoreWithNoMoreData() else mBinding.refreshLayout.finishLoadMore()
                        if (mPage == 0) {
                            if (datas.isNullOrEmpty()) showEmpty()
                        }
                    }
                })
            }
        }

    }

    private fun initBanner(list: List<HomeBannerBean>) {
        mHeadViewBinding.banner.setAdapter(object : BannerImageAdapter<HomeBannerBean?>(list) {
            override fun onBindView(holder: BannerImageHolder, data: HomeBannerBean?, position: Int,
                size: Int) {
                //图片加载自己实现
                Glide.with(holder.itemView).load(data?.imagePath)
                    .apply(RequestOptions.bitmapTransform(RoundedCorners(30))).into(holder.imageView)
            }
        }).addBannerLifecycleObserver(this) //添加生命周期观察者
            .setIndicator(CircleIndicator(this))
            .start()
    }

    private var mPage = 0
    private val pageSize = 20

    override fun requestData() {
        mViewModel.articleList(mPage, pageSize)
    }

    /**
     * 获取banner数据
     */
    private fun getBannerData() {
        mViewModel.homeBanner()
    }

    private fun initWidgets() {
        mBinding.rvList.run {
            adapter = mArticleAdapter
            //添加头布局
            val headView =
                LayoutInflater.from(mContext).inflate(R.layout.view_net_header, mBinding.rvList, false)
            mHeadViewBinding = ViewNetHeaderBinding.bind(headView)
            mArticleAdapter.addHeaderView(headView)
            addItemDecoration(RecycleViewDivider(mContext, LinearLayoutManager.VERTICAL, 1f.dp.toInt(), ResourceUtil.getColor(mContext, R.color.divider)))
        }
    }

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, NetActivity::class.java)
            context.startActivity(intent)
        }
    }


}